package org.jeecg.modules.demo.yyc.reportdaily.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.yyc.reportdaily.entity.PlatformDaily;
import org.jeecg.modules.demo.yyc.reportdaily.entity.Report;
import org.jeecg.modules.demo.yyc.reportdaily.mapper.PlatformDailyMapper;
import org.jeecg.modules.demo.yyc.reportdaily.service.DailyImportUtil;
import org.jeecg.modules.demo.yyc.reportdaily.service.IPlatformDailyService;
import org.jeecg.modules.demo.yyc.setting.businessplatform.entity.BusinessPlatform;
import org.jeecg.modules.demo.yyc.setting.businessplatform.service.IBusinessPlatformService;
import org.jeecg.modules.demo.yyc.setting.dailyItem.entity.DailyItem;
import org.jeecg.modules.demo.yyc.setting.dailyItem.service.IDailyItemService;
import org.jeecg.modules.demo.yyc.setting.store.entity.Store;
import org.jeecg.modules.demo.yyc.setting.store.service.IStoreService;
import org.jeecg.modules.demo.yyc.unit.DateUnit;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

/**
 * @Description: 运营日报
 * @Author: jeecg-boot
 * @Date:   2022-11-01
 * @Version: V1.0
 */
@Service
public class PlatformDailyServiceImpl extends ServiceImpl<PlatformDailyMapper, PlatformDaily> implements IPlatformDailyService {

    @Resource
    PlatformDailyMapper mapper;

    @Resource
    IDailyItemService dailyItemService;

    @Resource
    IBusinessPlatformService businessPlatformService;

    @Resource
    DailyImportUtil dailyImportUtil;

    @Resource
    IStoreService storeService;

    public void saveEntireDaily(List<PlatformDaily> platformDailies){
        check(platformDailies);
        String dailyGroupId = getDailyGroupId();
        platformDailies.forEach(item -> {
            item.setDailyId(dailyGroupId);
        });
        this.saveOrUpdateBatch(platformDailies);
    }

    @SneakyThrows
    public void importExcel(MultipartFile file)  {
        ImportParams params = new ImportParams();
        params.setHeadRows(0);
        params.setTitleRows(0);
        params.setSheetNum(1);
        List<Map<String, Object>> list = null;
        try (InputStream inputStream1 = file.getInputStream()){
            list = ExcelImportUtil.importExcel(inputStream1,Map.class,params);
            System.out.println(list);
        }

        if(list == null || list.size() == 0){
            return;
        }

        Map<String,Object> item = list.get(0);

        BusinessPlatform platform = dailyImportUtil.getPlatform(item, this);
        dailyImportUtil.checkExcelDailyItem(item,platform, this);
        List<PlatformDaily> platformDailies = dailyImportUtil.getPlatformDaily(list,platform);
        this.saveOrUpdateBatch(platformDailies);
    }

    @Override
    public Report getReports(IPage<HashMap<String,?>> page, String platformId) {
        Assert.notNull(platformId,"所属平台不能为空");
        String sql = QueryGenerator.installAuthJdbc(PlatformDaily.class);
        System.out.println("权限id："+sql);
        List<DailyItem> dailyItems = dailyItemService.getByPlatformId(platformId);
        IPage<HashMap<String,?>> result = mapper.getReports(page,platformId,dailyItems,sql);
        return new Report(result,dailyItems);
    }

    /**
     * 生成导入的模板
     * @param platformId 平台id
     * @return
     */
    public Workbook getTemplate(String platformId){
        Assert.notNull(platformId,"所属平台不能为空");
        BusinessPlatform platform = businessPlatformService.getById(platformId);
        List<DailyItem> dailyItems = dailyItemService.getByPlatformId(platformId);
        List<ExcelExportEntity> entityList = new ArrayList<>();
        List<Store> storeList = storeService.getStoreByPlatform(platformId);
        String[] storeNameArray = new String[storeList.size()];
        for (int i = 0; i < storeList.size(); i++) {
            storeNameArray[i] = storeList.get(i).getName();
        }

        entityList.add(new ExcelExportEntity("平台","平台"));
        entityList.add(new ExcelExportEntity("店铺","店铺"));
        entityList.add(new ExcelExportEntity("时间","create_time"));

        dailyItems.forEach(item -> {
            entityList.add(new ExcelExportEntity(item.getName(),item.getName()));
        });
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "sheetName"), entityList, new ArrayList<>());

        Sheet sheet = workbook.getSheetAt(0);
        DataValidation storeValidation = getExcelValidation(sheet, storeNameArray,1);
        DataValidation platFormValidation = getExcelValidation(sheet, new String[]{platform.getName()},0);
        sheet.addValidationData(storeValidation);
        sheet.addValidationData(platFormValidation);

        CellStyle style = workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("@"));
        for (int i = 0; i < entityList.size(); i++) {
            sheet.setDefaultColumnStyle(i, style);
        }

        return workbook;
    }

    private DataValidation getExcelValidation(Sheet sheet,String[] constraintArray, int colIndex) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        //设置下拉框数据
        DataValidationConstraint constraint = helper.createExplicitListConstraint(constraintArray);
        //设置生效的起始行、终止行、起始列、终止列
        CellRangeAddressList addressList = new CellRangeAddressList(1,2000,colIndex,colIndex);
        DataValidation validation = helper.createValidation(constraint,addressList);
        //适配xls和xlsx
        if(validation instanceof HSSFDataValidation){
            validation.setSuppressDropDownArrow(false);
        }else{
            validation.setSuppressDropDownArrow(true);
            validation.setShowErrorBox(true);
        }
        return validation;
    }

    public String getDailyGroupId(){
        Random random = new Random();
        return DateUnit.formattedNow("yyyyMMddHHmmssSSS")+"_"+Math.abs(random.nextInt());
    }

    /**
     * 检查所有的实体是否合法
     * @param platformDailies 日报实体
     */
    private void check(List<PlatformDaily> platformDailies){
        if(platformDailies.size() == 0){
            return;
        }
        String platformId = platformDailies.get(0).getPlatformId();
        String storeId = platformDailies.get(0).getStoreId();
        platformDailies.forEach(item ->{
            Assert.notNull(item.getPlatformId(),"所属平台不能为空");
            Assert.notNull(item.getStoreId(),"所属店铺不能为空");

            if(!platformId.equals(item.getPlatformId())){
                throw new RuntimeException("所属平台不一致");
            }
            if(!storeId.equals(item.getStoreId())){
                throw new RuntimeException("所属店铺不一致");
            }
        });
    }

}
